import * as types from '../constants/articleTypes'
import API from '../../api/request'

// 获取类型列表
export function articleCategary() {
	return dispatch => {
		dispatch(isCategaryFetching())
		categaryApi(dispatch)
	}
}

// 设置当前点击的类型
export function setCurTypeItem(item) {
	return dispatch => {
		dispatch(setTypeItem(item))
	}
}

// 根据id查找文章详情
export function articleDetail(id) {
	return dispatch => {
		articleDetailApi(id, dispatch)
		// dispatch(getArticleDetail(id))
	}
}

// 详情页面domain
export function getCanuseDomain() {
	return async dispatch => {
		let url = '/api/skip/articleLanding'
		let res = await API.get(url)
		if (global.isApiFetchingSuccess(res)) {
			dispatch(_apiDomainGetSuccess(res.data))
		} else {
			// dispatch(_apiBindGetError(res.message))
		}
	}
}

// 文章分类列表
async function categaryApi(dispatch) {
	const url = '/api/article/classify/list'
	let res = await API.post(url)
	if (res && res.code === '200') {
		let list = (res.data && res.data.list) || []
		// 过滤
		list = list.filter(item => {
			return !item.deleteFlag
		})
		// 排序
		list.sort((a, b) => {
			if (a.sort < b.sort) return -1
			if (a.sort > b.sort) return 1
			return 0
		})
		dispatch(setTypeItem(list[0]))
		dispatch(isCategaryFetchSuccess(list))
	} else {
		dispatch(isCategaryFetchError(res))
	}
}

// 获取文章列表
// async function articleList (dispatch, info) {
//   const url = '/api/article/list'
//   let res = await API.post(url)
//   if (res && res.code === 200) {
//     dispatch(isCategaryFetchSuccess(res.data && res.data.list))
//   } else {
//     dispatch(isCategaryFetchError(res))
//   }
// }

// 文章详情
async function articleDetailApi(id, dispatch) {
	const url = '/api/article/detail/' + id
	let res = await API.post(url)
	if (res && res.code === '200') {
		dispatch(isDetailFetchSuccess(res.data))
	} else {
		dispatch(isDetailFetchError(res))
	}
}

function isCategaryFetching() {
	return {
		type: types.CATEGARY_FETCHING
	}
}

function isCategaryFetchSuccess(list) {
	return {
		type: types.CATEGARY_FETCH_SUCCESS,
		list
	}
}

function isCategaryFetchError(err) {
	return {
		type: types.CATEGARY_FETCH_ERROR,
		err
	}
}

function isDetailFetchSuccess(detail) {
	return {
		type: types.DETAIL_FETCH_SUCCESS,
		detail
	}
}
function isDetailFetchError(err) {
	return {
		type: types.DETAIL_FETCH_ERROR,
		err
	}
}

function setTypeItem(item) {
	return {
		type: types.SET_TYPE_ITEM,
		item
	}
}

function _apiDomainGetSuccess(item) {
	return {
		type: types.DOMAIN_IN_SUCCESS,
		item
	}
}
